package com.bnlr.lrparking.appui.login;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.mine.setting.SettingActivity;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.ConstantFlag;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.SpConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.CloseLoginEvent;
import com.bnlr.lrparking.model.RegisterByWxResponse;
import com.bnlr.lrparking.model.VerifyCodeM;
import com.bnlr.lrparking.util.CountDownTimerUtils;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.widget.LoginDialog;
import com.bnlr.lrparking.widget.messagedialog.MessageDialog;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

/**
 * 注册界面
 * 普通注册  车位主注册
 * 微信用户绑定手机号
 *
 * @author hp
 * @date 2017/8/12
 */

public class RegisterActivity extends BaseActivity {

    private RelativeLayout rela_nav_back;
    private TextView tv_nav_title, tv_verifica, tv_clause;
    /**
     * 手机号，验证码，密码
     */
    private ClearEditText ed_register_phone, ed_register_verifica, ed_register_pwd;
    private String phone = "", verifica = "", pwd = "";
    private TextView tv_login_btn;
    private RelativeLayout rl_agree;
    private CheckBox checkBox;
    private ImageView img_register_hide;
    private int flag_new = 1;

    private int registerType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        // 1 注册  2 绑定手机号
        registerType = getIntent().getIntExtra("registerType", 1);
        setViewType(registerType);
    }

    private void initView() {
        rela_nav_back = (RelativeLayout) findViewById(R.id.rela_nav_back);
        tv_nav_title = (TextView) findViewById(R.id.tv_nav_title);
        tv_verifica = (TextView) findViewById(R.id.tv_register_verifica);
        ed_register_phone = (ClearEditText) findViewById(R.id.ed_register_phone);
        ed_register_verifica = (ClearEditText) findViewById(R.id.ed_register_verifica);
        ed_register_pwd = (ClearEditText) findViewById(R.id.ed_register_pwd);
        tv_login_btn = (TextView) findViewById(R.id.tv_login_btn);
        rl_agree = (RelativeLayout) findViewById(R.id.rl_agree);
        checkBox = (CheckBox) findViewById(R.id.agree_clause);
        tv_clause = (TextView) findViewById(R.id.tv_clause);
        img_register_hide = (ImageView) findViewById(R.id.img_register_hide);
        rl_agree.setOnClickListener(this);
        rela_nav_back.setOnClickListener(this);
        tv_verifica.setOnClickListener(this);
        tv_login_btn.setOnClickListener(this);
        img_register_hide.setOnClickListener(this);
        ed_register_phone.addTextChangedListener(this);
        tv_clause.setOnClickListener(this);
        ed_register_verifica.addTextChangedListener(mTextWatcher);
        ed_register_pwd.addTextChangedListener(mTextWatcher);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tipDialog!=null){
            if (tipDialog.isShowing()){
                tipDialog.dismiss();
            }
        }
    }

    /**
     * 页面初始化
     * 显示类型
     *
     * @param type 1 注册
     *             2 绑定手机号
     */
    private void setViewType(int type) {
        if (type == 1) {
            tv_nav_title.setText("注册");
            tv_login_btn.setText("注册");
        } else {
            tv_nav_title.setText("绑定手机号");
            tv_login_btn.setText("绑定手机号");
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rela_nav_back:
                if (registerType == ConstantFlag.INTEGER_FLAG_TWO) {
                    AppConfig.getInstance().clearUserInfo();
                    JPushInterface.setAlias(RegisterActivity.this, 2019, "");
                }
                finish();
                break;
            case R.id.rl_agree:
                if (checkBox.isChecked()) {
                    checkBox.setChecked(false);
                    if (!verifica.equals("") && !pwd.equals("")) {
                        tv_login_btn.setEnabled(true);
                    }

                } else {
                    checkBox.setChecked(true);
                    tv_login_btn.setEnabled(false);
                }
                break;
            case R.id.tv_clause:
                Intent intent = new Intent(baseContext, WebActivity.class);
                intent.putExtra("tag", 3);
                startActivity(intent);
                break;
            case R.id.tv_register_verifica:
                sendYzm();
                break;
            case R.id.tv_login_btn:
                if (!RegexUtils.isMobileExact(phone)) {
                    ToastUtils.showShort("手机格式不正确");
                } else {
                    if (registerType == 1) {
                        getRegister();
                    } else {
                        weChatBindPhone();
                    }
                }
                break;
            case R.id.img_register_hide:
                if (flag_new == 1) {
                    flag_new = 2;
                    img_register_hide.setImageResource(R.mipmap.login_icon05);
                    ed_register_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    flag_new = 1;
                    img_register_hide.setImageResource(R.mipmap.login_icon04);
                    ed_register_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        super.afterTextChanged(s);
        phone = ed_register_phone.getText().toString();
        if (RegexUtils.isMobileExact(phone)) {
            tv_verifica.setEnabled(true);
            tv_verifica.setBackgroundResource(R.mipmap.verificationbox_click);
        } else {
            tv_verifica.setBackgroundResource(R.mipmap.verificationbox_dis);
            tv_verifica.setEnabled(false);
        }

    }

    /**
     * 判断验证码的监听
     */
    private TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {

            verifica = ed_register_verifica.getText().toString();
            pwd = ed_register_pwd.getText().toString();

            if (!verifica.equals("") && !pwd.equals("") && !checkBox.isChecked()) {
                tv_login_btn.setEnabled(true);
            } else {
                tv_login_btn.setEnabled(false);
            }

        }
    };

    /**
     * 验证码请求
     */
    private void sendYzm() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "sendValidateMCD");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("phone", phone);
            mRequest.add("flag", "0");
            // 添加到请求队列
            CallServer.getRequestInstance().add(RegisterActivity.this, mRequest,
                    new CustomHttpListener<VerifyCodeM>(RegisterActivity.this, true, VerifyCodeM.class) {
                        @Override
                        public void doWork(VerifyCodeM data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {
                                // {"msgcode":"1","msg":"成功","data":{"code":"06641"}}
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    setVerifica(tv_verifica);
                                } else {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setVerifica(TextView verifica) {
        CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(verifica, 60000, 1000);
        mCountDownTimerUtils.start();
    }

    /**
     * 注册
     */
    private void getRegister() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "UserRegister");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("phone", phone);
            mRequest.add("pwd", pwd);
            mRequest.add("code", verifica);

            // 添加到请求队列
            CallServer.getRequestInstance().add(RegisterActivity.this, mRequest,
                    new CustomHttpListener<VerifyCodeM>(RegisterActivity.this, true, VerifyCodeM.class) {
                        @Override
                        public void doWork(VerifyCodeM data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                tv_login_btn.setEnabled(true);
                                if ("1".equals(code)) {
                                    JSONObject object = obj.getJSONObject("data");
                                    AppConfig.getInstance().putString("uid", object.getString("uid"));
                                    AppConfig.getInstance().putString("userName", object.getString("userName"));
                                    AppConfig.getInstance().putString("nickName", object.getString("nickName"));
                                    AppConfig.getInstance().putString("realName", object.getString("realName"));
                                    AppConfig.getInstance().putString("password", object.getString("password"));
                                    AppConfig.getInstance().putString("salt", object.getString("salt"));
                                    AppConfig.getInstance().putString("photo", object.getString("photo"));
                                    AppConfig.getInstance().putString("paypassword", object.getString("paypassword"));
                                    AppConfig.getInstance().putString("status", object.getString("status"));
                                    AppConfig.getInstance().putString("sharevalue", object.getString("sharevalue"));
                                    AppConfig.getInstance().putString("sharevalue_u", object.getString("sharevalue_u"));
                                    AppConfig.getInstance().putString("parktime", object.getString("parktime"));
                                    AppConfig.getInstance().putString("incomevalue", object.getString("incomevalue"));
                                    AppConfig.getInstance().putString("isRealNameAuth", object.getString("isRealNameAuth"));
                                    AppConfig.getInstance().putString("idcard", object.getString("idcard"));
                                    AppConfig.getInstance().putString("sex", object.getString("sex"));
                                    AppConfig.getInstance().putBoolean("isLogin", true);
                                    finish();
                                } else {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }

                                if ("1".equals(code)) {
                                    CommonUtil.showToask(RegisterActivity.this, obj.getString("msg"));
                                    finish();
                                } else {
                                    CommonUtil.showToask(RegisterActivity.this, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 微信用户绑定手机号和密码
     */
    private void weChatBindPhone() {

        String unionid = AppConfig.getInstance().getString(SpConstant.KEY_WX_UNIONID, "");

        mRequest = NoHttp.createStringRequest(Urls.WE_CHAT_BIND_PHONE, LrConstant.POST);
        mRequest.add("unionid", unionid);
        mRequest.add("phone", phone);
        mRequest.add("password", pwd);
        mRequest.add("CheckCode", verifica);

        CallServer.getRequestInstance().add(RegisterActivity.this, mRequest,
                new CustomHttpListener<RegisterByWxResponse>(RegisterActivity.this, true, RegisterByWxResponse.class) {
                    @Override
                    public void doWork(RegisterByWxResponse data, String code) {
                        if (data != null) {
                            LogUtils.i(data.toString());
                            switch (data.getErrorCode()) {
                                case 0:
                                    saveUserInfo(data);
                                    EventBus.getDefault().post(new CloseLoginEvent(3));
                                    finish();
                                    break;
                                case 1000:
                                    if (data.getMsg().contains("验证码错误")){
                                        showTipDialog(data.getMsg(), new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                tipDialog.dismiss();
                                            }
                                        });
                                    }else {
                                        showTipDialog(data.getMsg(), new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                AppConfig.getInstance().clearUserInfo();
                                                JPushInterface.setAlias(RegisterActivity.this, 2019, "");
                                                tipDialog.dismiss();
                                                finish();
                                            }
                                        });
                                    }
                                    break;
                                case 1:
                                    ToastUtils.showShort(data.getMsg());
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }, false);
    }


    private AlertDialog tipDialog;

    private void showTipDialog(String msg, View.OnClickListener listener) {

        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this, R.style.TipDialog);
        tipDialog = builder.create();

        View contentView = View.inflate(RegisterActivity.this, R.layout.dialog_message, null);
        TextView title = (TextView) contentView.findViewById(R.id.tv_dialog_message_title);
        TextView message = (TextView) contentView.findViewById(R.id.tv_dialog_message_message);
        TextView cancel = (TextView) contentView.findViewById(R.id.tv_dialog_message_cancel);
        TextView confirm = (TextView) contentView.findViewById(R.id.tv_dialog_message_confirm);

        title.setText("提示");
        message.setText(msg);
        cancel.setOnClickListener(listener);
        confirm.setText("再试试");
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tipDialog.dismiss();
            }
        });

        tipDialog.setCancelable(true);
        tipDialog.show();

        tipDialog.setContentView(contentView);
    }

    /**
     * 保存用户信息
     *
     * @param userByWx
     */
    private void saveUserInfo(RegisterByWxResponse userByWx) {
        AppConfig.getInstance().putBoolean("isLogin", true);
        AppConfig.getInstance().putBoolean(SpConstant.KEY_IS_WX_LOGIN, true);
        AppConfig.getInstance().putString("uid", String.valueOf(userByWx.getData().getUid()));
        AppConfig.getInstance().putString("userName", userByWx.getData().getUserName());
        AppConfig.getInstance().putString("nickName", userByWx.getData().getNickName());
        AppConfig.getInstance().putString("realName", userByWx.getData().getRealName());
        AppConfig.getInstance().putString("password", userByWx.getData().getPassword());
        AppConfig.getInstance().putString("salt", userByWx.getData().getSalt());
        AppConfig.getInstance().putString("photo", userByWx.getData().getPhoto());
        AppConfig.getInstance().putString("paypassword", userByWx.getData().getPaypassword());
        AppConfig.getInstance().putString("status", String.valueOf(userByWx.getData().getStatus()));
        AppConfig.getInstance().putString("sharevalue", String.valueOf(userByWx.getData().getSharevalue()));
        AppConfig.getInstance().putString("sharevalue_u", String.valueOf(userByWx.getData().getSharevalue_u()));
        AppConfig.getInstance().putString("parktime", String.valueOf(userByWx.getData().getParktime()));
        AppConfig.getInstance().putString("incomevalue", String.valueOf(userByWx.getData().getIncomevalue()));
        AppConfig.getInstance().putString("isRealNameAuth", String.valueOf(userByWx.getData().getIsRealNameAuth()));
        AppConfig.getInstance().putString("idcard", userByWx.getData().getIdcard());
        AppConfig.getInstance().putString("sex", String.valueOf(userByWx.getData().getSex()));
        // 发送通知
        EventBus.getDefault().post(new CloseLoginEvent(3));
        // 设置极光推送别名
        JPushInterface.setAlias(getApplicationContext(), 2019, userByWx.getData().getUserName());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            AppConfig.getInstance().clearUserInfo();
            JPushInterface.setAlias(RegisterActivity.this, 2019, "");
        }
        return super.onKeyDown(keyCode, event);
    }
}
